package com.tian.view.draw.shader

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Shader
import android.util.AttributeSet
import com.tian.util.view.DisplayUtil
import com.tian.view.R
import com.tian.view.common.BaseClickView

/**
 * @author tiansongtao
 * @date 2023/1/5 15:45
 */
class BitmapShaderView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
        BaseClickView(context, attrs, defStyleAttr) {

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context) : this(context, null)

    private val paint = Paint()
    private val textPaint = Paint().apply {
        color = Color.BLACK
        style = Paint.Style.FILL_AND_STROKE
        textSize = DisplayUtil.spToPx(18f)
        isAntiAlias = true
        isFakeBoldText = true
        textAlign = Paint.Align.CENTER
    }
    private var tileMode = Shader.TileMode.MIRROR
    private var index = 0
    private val bitmap: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.jingdong)
    private var showHalf = false


    /**
     * Shader的填充模式：当图片小于view大小时需要填充多余的空间
     *  [Shader.TileMode.MIRROR]: 重复使用镜像模式来填充多余空间
     *  [Shader.TileMode.REPEAT]: 重复原图填充多余空间
     *  [Shader.TileMode.CLAMP]: 用图像边缘彩色来填充多余空间
     * 注意：填充总是先沿Y轴填充后沿X轴填充
     *
     * 限制范围绘制，可以看到只显示了原来的部分内容，可见shader总是从
     * view的左上角开始绘制的。
     */
    override fun onDraw(canvas: Canvas) {
        paint.shader = BitmapShader(bitmap, tileMode, tileMode)
        if (showHalf) {
            canvas.drawRect(width.toFloat() / 4, height.toFloat() / 4,
                    width.toFloat() / 4 * 3, height.toFloat() / 4 * 3, paint)
        } else {
            canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
        }
        canvas.drawText("点击切换填充模式", width.toFloat() / 2, 100f, textPaint)
        canvas.drawText("当前模式为${tileMode.name}", width.toFloat() / 2, 200f, textPaint)
        if (showHalf) {
            canvas.drawText("使用范围绘制确定Shader绘制起始位置", width.toFloat() / 2, 300f, textPaint)
        }
    }

    override fun singleClick() {
        super.singleClick()
        index++
        if (index > 3) {
            index = 0
        }
        showHalf = false
        tileMode = when (index) {
            0 -> Shader.TileMode.MIRROR
            1 -> Shader.TileMode.CLAMP
            2 -> Shader.TileMode.REPEAT
            else -> {
                showHalf = true
                Shader.TileMode.REPEAT
            }
        }
        postInvalidate()
    }



}